執行緒(thread)是個非常重要的觀念,在實際操作前,先來了解不同名詞之間的關係。
三者間的關係圖如下:
程式(program)
↓ 開始運行
行程/程序(program)
|
| ┌─> 執行緒一(thread 1)
└─|
└─> 執行緒二(thread 2)
從 C++ 11 起,可以直接用標頭檔 <thread> 來操作執行緒,範例用法如下:
#include <iostream>
#include <thread>
void printMessage() {
std::cout << "Hello from the new thread!" << std::endl;
}
int main()
{
// 在還沒有新執行緒時,只有主執行緒執行這裡
std::cout << "Originally in the main thread." << std::endl;
// 建立一個新執行緒物件 myThread,並指定 printMessage 為執行內容
std::thread myThread(printMessage);
// 這時主執行緒與新執行緒同時進行
// 用 join() 使主執行緒等待 myThread 這個新執行緒執行完畢
myThread.join();
// 這時只有新執行緒在跑,主執行緒暫停
// 新執行緒 myThread 結束後,主執行緒繼續執行,印出下列訊息
std::cout << "Back in the main thread." << std::endl;
return 0;
}
程式碼執行流程如下:
main() 函數。main() 函數的 std::cout << "Originally in the main thread." << std::endl;。myThread,其內容為 printMessage() 函數;此時主執行緒與新執行緒同時進行。.join() ,主執行緒會等待新執行緒執行完畢。main() 函數的 std::cout << "Back in the main thread." << std::endl;。執行結果如下:
Originally in the main thread.
Hello from the new thread!
Back in the main thread.
在上述程式碼中,共有執行 main() 函數的主執行緒,以及 myThread() 這個新執行緒,因此為多執行緒,透過 join() 協調。
如果沒有 join(),則新執行緒在還沒執行完時,即可能因主執行緒執行完畢而跟著被強制終止,使程式提早結束。